package com.hgyc.mom.data.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hgyc.mom.common.context.FileServiceContext;
import com.hgyc.mom.common.exception.BizException;
import com.hgyc.mom.common.exception.file.FileException;
import com.hgyc.mom.common.util.file.FileUtils;
import com.hgyc.mom.common.vo.Result;
import com.hgyc.mom.core.mybatis.QueryWrapperUtil;
import com.hgyc.mom.data.entity.GoviewFile;
import com.hgyc.mom.data.entity.GoviewProject;
import com.hgyc.mom.data.entity.GoviewProjectData;
import com.hgyc.mom.data.service.GoviewFileService;
import com.hgyc.mom.data.service.GoviewProjectDataService;
import com.hgyc.mom.data.service.GoviewProjectService;
import com.hgyc.mom.data.vo.GoviewProjectParam;
import com.hgyc.mom.data.vo.GoviewProjectVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;

import static com.hgyc.mom.common.vo.Result.error;

/**
 * 大屏项目Controller
 *
 * @author fwj
 * @since 2025-08-08
 */
@Slf4j
@Tag(name = "大屏项目控制器", description = "大屏项目控制器")
@RestController
@RequestMapping("/goview/project")
public class GoviewProjectController {
    @Autowired
    private GoviewProjectService goviewProjectService;

    @Autowired
    private GoviewProjectDataService goviewProjectDataService;

    @Autowired
    private GoviewFileService goviewFileService;

    @Autowired
    private FileServiceContext fileServiceContext;

    @Operation(summary = "查询大屏项目列表", description = "查询大屏项目列表")
    @PostMapping("/pageList")
    public Result<IPage<GoviewProject>> pageList(@Parameter(description = "查询参数") @RequestBody GoviewProjectParam goviewProjectParam) {
        Page<GoviewProject> page = new Page<>(goviewProjectParam.getPage(), goviewProjectParam.getPageSize());
        GoviewProject goviewProject = new GoviewProject();
        BeanUtils.copyProperties(goviewProjectParam, goviewProject);
        QueryWrapper<GoviewProject> wrapper = QueryWrapperUtil.build(goviewProject);
        IPage<GoviewProject> list = goviewProjectService.page(page, wrapper);
        return Result.success(list);
    }

    @Operation(summary = "获取大屏项目详细信息", description = "获取大屏项目详细信息")
    @GetMapping(value = "/{id}")
    public Result getInfo(@Parameter(description = "大屏项目ID") @PathVariable("id") Long id) {
        return Result.success(goviewProjectService.getById(id));
    }
    @Operation(summary = "新增大屏项目", description = "新增大屏项目")
    @PostMapping
    public Result<?> save(@Parameter(description = "大屏项目") @RequestBody GoviewProjectVo goviewProject) {
        goviewProjectService.saveProject(goviewProject);
        return Result.success("保存成功", goviewProject.getId());
    }

    @Operation(summary = "修改大屏项目", description = "修改大屏项目")
    @PutMapping
    public Result<?> update(@Parameter(description = "大屏项目") @RequestBody GoviewProjectVo goviewProject) {
        goviewProjectService.updateProject(goviewProject);
        return Result.success("保存成功", goviewProject.getId());
    }

    @Operation(summary = "删除大屏项目", description = "删除大屏项目")
    @DeleteMapping
    public Result<?> remove(@Parameter(description = "删除ID") @RequestParam("ids") Long[] ids) {
        return Result.success(goviewProjectService.removeByIds(Arrays.asList(ids)));
    }

    @Operation(summary = "项目重命名", description = "项目重命名")
    @PostMapping("/rename")
    public Result rename(@RequestBody GoviewProject goviewProject)
    {
        LambdaUpdateWrapper<GoviewProject> updateWrapper= new LambdaUpdateWrapper<>();
        updateWrapper.eq(GoviewProject::getId, goviewProject.getId());
        updateWrapper.set(GoviewProject::getProjectName, goviewProject.getProjectName());
        goviewProjectService.update(updateWrapper);
        return Result.success();
    }


    @Operation(summary="发布/取消项目状态", description="Customize Toolbar…")
    @PutMapping("/publish")
    public Result updateVisible(@RequestBody GoviewProject goviewProject){
        if (goviewProject.getId() == null) {
            throw new BizException("项目ID不能为空！");
        }
        if(goviewProject.getState()==1||goviewProject.getState()==0) {
            LambdaUpdateWrapper<GoviewProject> updateWrapper=new LambdaUpdateWrapper<GoviewProject>();
            updateWrapper.eq(GoviewProject::getId, goviewProject.getId());
            updateWrapper.set(GoviewProject::getState, goviewProject.getState());
            goviewProjectService.update(updateWrapper);
            return Result.success();
        }
        return Result.error("警告非法字段");
    }


    @Operation(summary = "获取项目存储数据", description = "获取项目存储数据")
    @GetMapping("/getData")
    public Result getData(@RequestParam("projectId") Long projectId)
    {
        GoviewProject goviewProject= goviewProjectService.getById(projectId);
        GoviewProjectVo goviewProjectVo=new GoviewProjectVo();
        BeanUtils.copyProperties(goviewProject,goviewProjectVo);

        GoviewProjectData blogText=goviewProjectDataService.getByProjectId(projectId);
        if(blogText!=null) {
            goviewProjectVo.setContent(blogText.getContent());
        }
        return Result.success(goviewProjectVo);

    }

    /**
     * 上传文件
     * @param file 文件流对象
     * @return 文件信息
     */
    @Operation(summary="上传文件", description="上传文件")
    @PostMapping("/upload")
    public Result upload(@RequestParam("file") MultipartFile file) {
        String fileName = file.getOriginalFilename();
        //默认文件格式
        String suffixName = ".png";
        String mediaKey="";
        Long filesize= file.getSize();
        //文件名字
        String fileSuffixName="";
        if(fileName.lastIndexOf(".")!=-1) {//有后缀
            suffixName = fileName.substring(fileName.lastIndexOf(".")).toLowerCase();
        }

        String path = fileServiceContext.uploadFile(file, "goview");

        GoviewFile goviewFile=new GoviewFile();
        goviewFile.setFileName(fileName);
        goviewFile.setFileSize(filesize);
        goviewFile.setFileSuffix(fileSuffixName);
        goviewFile.setFilePath(path);
        goviewFileService.save(goviewFile);
        return Result.success("上传成功", goviewFile.getId());
    }

    /**
     * 下载文件
     *
     * @param attachmentId 附件ID
     */
    @GetMapping("/download/{fileId}")
    public void fileDownload(@PathVariable("fileId") Long fileId, HttpServletResponse response, HttpServletRequest request)
    {
        try
        {
            GoviewFile goviewFile = goviewFileService.getById(fileId);
            if (goviewFile == null) {
                throw new FileException("获取文件失败！");
            }

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, goviewFile.getFileName());

            byte[] bytes = fileServiceContext.downloadFile(goviewFile.getFilePath());

            FileUtils.writeBytes(bytes, response.getOutputStream());

        }catch (Exception e){
            log.error("下载文件失败", e);
            throw new FileException("下载文件失败！", e);
        }
    }
}
